package com.example.shutdown_v1.controller;

import com.example.shutdown_v1.entity.DailyInspectionRecord;
import com.example.shutdown_v1.entity.Sensor;
import com.example.shutdown_v1.entity.Shop;
import com.example.shutdown_v1.repository.SensorRepository;
import com.example.shutdown_v1.repository.ShopRepository;
import com.example.shutdown_v1.service.DailyInspectionService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 店铺管理API
 */
@Slf4j
@RestController
@RequestMapping("/api/shop")
@RequiredArgsConstructor
public class ShopController {

    private final ShopRepository shopRepository;
    private final SensorRepository sensorRepository;
    private final DailyInspectionService inspectionService;

    /**
     * 创建店铺
     * POST /api/shop/create
     */
    @PostMapping("/create")
    public ResponseEntity<Map<String, Object>> createShop(@RequestBody ShopRequest request) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 检查店铺编码是否已存在
            if (shopRepository.findByCode(request.getCode()).isPresent()) {
                response.put("success", false);
                response.put("message", "店铺编码已存在");
                return ResponseEntity.badRequest().body(response);
            }
            
            Shop shop = new Shop();
            shop.setName(request.getName());
            shop.setCode(request.getCode());
            shop.setLocation(request.getLocation());
            shop.setResponsiblePerson(request.getResponsiblePerson());
            shop.setContactPhone(request.getContactPhone());
            shop.setClosingTime(request.getClosingTime());
            shop.setStatus(1);
            
            shopRepository.save(shop);
            
            response.put("success", true);
            response.put("message", "店铺创建成功");
            response.put("shop", shop);
            
            log.info("[店铺] 创建成功: {} ({})", shop.getName(), shop.getCode());
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("店铺创建失败", e);
            response.put("success", false);
            response.put("message", "创建失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 查询店铺列表
     * GET /api/shop/list?status={status}
     */
    @GetMapping("/list")
    public ResponseEntity<Map<String, Object>> listShops(
            @RequestParam(required = false) Integer status) {
        
        List<Shop> shops;
        if (status != null) {
            shops = shopRepository.findByStatus(status);
        } else {
            shops = shopRepository.findAll();
        }
        
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("shops", shops);
        response.put("count", shops.size());
        
        return ResponseEntity.ok(response);
    }

    /**
     * 查询店铺详情
     * GET /api/shop/detail/{shopId}
     */
    @GetMapping("/detail/{shopId}")
    public ResponseEntity<Map<String, Object>> getShopDetail(@PathVariable Long shopId) {
        var shopOpt = shopRepository.findById(shopId);
        
        if (shopOpt.isEmpty()) {
            Map<String, Object> error = new HashMap<>();
            error.put("success", false);
            error.put("message", "店铺不存在");
            return ResponseEntity.notFound().build();
        }
        
        Shop shop = shopOpt.get();
        
        // 获取该店铺的传感器列表
        List<Sensor> sensors = sensorRepository.findByShopId(shopId);
        
        // 将传感器转换为统一的监控设备列表
        List<Map<String, Object>> devices = new ArrayList<>();
        
        // 1. 添加所有传感器
        for (Sensor sensor : sensors) {
            Map<String, Object> device = new HashMap<>();
            device.put("deviceType", "sensor");
            device.put("deviceId", sensor.getSensorId());
            device.put("sensorId", sensor.getSensorId());
            device.put("installPosition", sensor.getInstallPosition());
            device.put("installPositionName", sensor.getInstallPositionName());
            device.put("sensorModel", sensor.getSensorModel());
            device.put("lastOnlineTime", sensor.getLastOnlineTime());
            device.put("isOffline", sensor.getIsOffline());
            devices.add(device);
        }
        
        // 断路器已下线：不再将断路器加入设备列表
        
        // 获取最新巡检记录
        DailyInspectionRecord latestInspection = inspectionService.getLatestInspection(shopId);
        
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("shop", shop);
        response.put("sensors", sensors);  // 保留传感器列表向后兼容
        response.put("devices", devices);  // 新增：统一的监控设备列表（传感器+断路器）
        response.put("sensorCount", sensors.size());
        response.put("deviceCount", devices.size());
        response.put("latestInspection", latestInspection);
        
        return ResponseEntity.ok(response);
    }

    /**
     * 手动触发店铺巡检
     * POST /api/shop/inspect/{shopId}
     */
    @PostMapping("/inspect/{shopId}")
    public ResponseEntity<Map<String, Object>> manualInspect(@PathVariable Long shopId) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            DailyInspectionRecord record = inspectionService.performInspection(shopId);
            
            if (record == null) {
                response.put("success", false);
                response.put("message", "巡检失败，店铺不存在或无传感器");
                return ResponseEntity.badRequest().body(response);
            }
            
            response.put("success", true);
            response.put("message", "巡检完成");
            response.put("inspection", record);
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("巡检失败", e);
            response.put("success", false);
            response.put("message", "巡检失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 请求体：创建店铺
     */
    @lombok.Data
    public static class ShopRequest {
        private String name;
        private String code;
        private String location;
        private String responsiblePerson;
        private String contactPhone;
        private LocalTime closingTime;
    }
}

